//
//  VeriftyViewController.m
//  DaiShengInvest
//
//  Created by 张睿 on 2017/6/29.
//  Copyright © 2017年 davinci. All rights reserved.
//

#import "VeriftyViewController.h"
#import "AddIDCardImageViewController.h"

@interface VeriftyViewController ()<UITextFieldDelegate>

@property (nonatomic, weak)UIImageView * backImageView;

@property (nonatomic, weak)UILabel * nameLabel;

@property (nonatomic, weak)UITextField * nameField;

@property (nonatomic, weak)UIView * oneLineView;

@property (nonatomic, weak)UILabel * cardNumberLabel;

@property (nonatomic, weak)UITextField * cardNumberField;

@property (nonatomic, weak)UIView * twoLineView;

@property (nonatomic, weak)UILabel * showLabel;

@property (nonatomic, weak)UIButton * nextButton;

@property (nonatomic, copy)NSString * responseCode;

@property (nonatomic, copy)NSString * nameString;

@property (nonatomic, copy)NSString * idCardNumString;

@property (nonatomic, weak)UILabel * stateLabel;

@property (nonatomic, copy)NSString * canEdit;

@end

@implementation VeriftyViewController


- (void)viewWillAppear:(BOOL)animated{
    
    [self loadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    [self loadData];
    [self setupNavBar];
    [self setupUI];
}


- (void)loadData{
    
    [[NetworkTool sharedTools] POST:@"user/audit-info" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        
        self.responseCode = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        
        if ([self.responseCode isEqualToString:@"0"]) {
            
            NSDictionary * paramDict = responseObject[@"param"];
            
            self.responseCode = [NSString stringWithFormat:@"%@",paramDict[@"state"]];
            self.nameString = [NSString stringWithFormat:@"%@",paramDict[@"fullname"]];
            self.idCardNumString = [NSString stringWithFormat:@"%@",paramDict[@"cardNo"]];
            
            [self setupUI];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"%@",error);
    }];
    
}


- (void)setupNavBar{
    
    self.title = @"实名认证";
    
    UIButton * backButton = [[UIButton alloc] init];
    
    backButton.frame = CGRectMake(15 * SCREENH6, 5 * SCREENH6, 12 * SCREENH6, 20 * SCREENH6);
    [backButton setImage:[UIImage imageNamed:@"1返回"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToAccountView) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = leftButton;
}


- (void)setupUI{
    
    UIImageView * backImage = [[UIImageView alloc] init];
    
    backImage.image = [UIImage imageNamed:@"背景"];
    
    self.backImageView = backImage;
    
    [self.view addSubview:self.backImageView];
    
    
    UILabel * nameLabel = [[UILabel alloc] init];
    
    nameLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:15 * SCREENH6];
    nameLabel.textColor = ColorWithRGB(0xffffff);
    nameLabel.text = @"姓名";
    
    self.nameLabel = nameLabel;
    
    [self.view addSubview:self.nameLabel];
    
    UITextField * moneyCardField = [[UITextField alloc] init];
    
    moneyCardField.borderStyle = UITextBorderStyleNone;
    moneyCardField.backgroundColor = [UIColor clearColor];
    moneyCardField.delegate = self;
    
    //设置光标颜色
    moneyCardField.tintColor = ColorWithRGB(0x646464);
    //修改占位符文字颜色
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSForegroundColorAttributeName] = ColorWithRGB(0x646464);
    attrs[NSFontAttributeName] = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    if ([self.responseCode isEqualToString:@"1"]) {
        
         moneyCardField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.nameString attributes:attrs];
    }else{
        
         moneyCardField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入真实姓名" attributes:attrs];
    }
   
    moneyCardField.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    moneyCardField.textColor = ColorWithRGB(0x646464);
    
    
    
    self.nameField = moneyCardField;
    
    [self.view addSubview:self.nameField];
    
    UIView * oneLineView = [UIView new];
    
    oneLineView.backgroundColor = [UIColor whiteColor];
    oneLineView.alpha = 0.1;
    
    self.oneLineView = oneLineView;
    
    [self.view addSubview:self.oneLineView];
    
    
    UILabel * cardNumberLabel = [[UILabel alloc] init];
    
    cardNumberLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:15 * SCREENH6];
    cardNumberLabel.textColor = ColorWithRGB(0xffffff);
    cardNumberLabel.text = @"身份证号码";
    
    self.cardNumberLabel = cardNumberLabel;
    
    [self.view addSubview:self.cardNumberLabel];
    
    UITextField * cardNumberField = [[UITextField alloc] init];
    
    cardNumberField.borderStyle = UITextBorderStyleNone;
    cardNumberField.backgroundColor = [UIColor clearColor];
    cardNumberField.delegate = self;
    
    //设置光标颜色
    cardNumberField.tintColor = ColorWithRGB(0x646464);
    if ([self.responseCode isEqualToString:@"1"]) {
        
        cardNumberField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.idCardNumString attributes:attrs];
    }else{
        cardNumberField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入身份证号码" attributes:attrs];
    }
    cardNumberField.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    cardNumberField.textColor = ColorWithRGB(0x646464);
    
    self.cardNumberField = cardNumberField;
    
    [self.view addSubview:self.cardNumberField];
    
    UIView * twoLineView = [UIView new];
    
    twoLineView.backgroundColor = [UIColor whiteColor];
    twoLineView.alpha = 0.1;
    
    self.twoLineView = twoLineView;
    
    [self.view addSubview:self.twoLineView];
    
    UILabel * showLabel = [UILabel new];
    
    showLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:12 * SCREENH6];
    showLabel.textColor = ColorWithRGB(0xfef4e75);
    showLabel.text = @"*一张身份证只能绑定一个账号，请填写本人真实信息，核实后将不可更改";
    showLabel.numberOfLines = 0;
    self.canEdit = @"canEdit";
    
    if ([self.responseCode isEqualToString:@"0"]) {
        
        showLabel.hidden = NO;
    }else{
        showLabel.hidden = YES;
    }
    
    self.showLabel = showLabel;
    
    [self.view addSubview:self.showLabel];
    
    UIButton * nextButton = [[UIButton alloc] init];
    
    [nextButton setTitle:@"下一步" forState:UIControlStateNormal];
    nextButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:17 * SCREENH6];//[UIFont systemFontOfSize:15];
//    [nextButton setBackgroundColor:ColorWithRGB(0x979797)];
    [nextButton setBackgroundImage:[UIImage imageNamed:@"注册"] forState:UIControlStateNormal];
    nextButton.layer.borderColor = [[UIColor blackColor] CGColor];
    //边框宽度
    nextButton.layer.borderWidth =1.0f;
    //处理圆角
    nextButton.layer.cornerRadius =5.0f;
    [nextButton setTitleColor:ColorWithRGB(0xffffff) forState:UIControlStateNormal];
    [nextButton addTarget:self action:@selector(didNextButton) forControlEvents:UIControlEventTouchUpInside];
    
    if ([self.responseCode isEqualToString:@"1"] || [self.responseCode isEqualToString:@"2"]) {
        
        nextButton.hidden = YES;
    }
    
    self.nextButton = nextButton;
    
    [self.view addSubview:self.nextButton];
    
    
    UILabel * stateLabel = [UILabel new];
    
    stateLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16 * SCREENH6];
    stateLabel.textColor = ColorWithRGB(0xfef4e75);
    stateLabel.numberOfLines = 0;
    stateLabel.hidden = YES;
    if ([self.responseCode isEqualToString:@"1"]) {
        stateLabel.text = @"审核中...";
        stateLabel.hidden = NO;
        
        self.canEdit = @"can'tEdit";
        
    }else if([self.responseCode isEqualToString:@"3"]){
        stateLabel.text = @"审核未通过，请重新提交审核！";
        stateLabel.hidden = NO;
    }else if([self.responseCode isEqualToString:@"2"]){
        stateLabel.text = @"已认证！";
        stateLabel.hidden = NO;
    }
    
    self.stateLabel = stateLabel;
    
    [self.view addSubview:self.stateLabel];
    
}


- (void)viewDidLayoutSubviews{
    
    [self.backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.bottom.mas_equalTo(self.view);
    }];
    
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view).offset(15 * SCREENH6);
        make.top.mas_equalTo(self.view).offset(89 * SCREENH6);
    }];
    
    [self.nameField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view).offset(140 * SCREENH6);
        make.centerY.mas_equalTo(self.nameLabel);
        make.height.mas_equalTo(self.nameLabel);
        make.width.mas_equalTo(200 * SCREENH6);
    }];
    
    [self.oneLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).offset(129 * SCREENH6);
        make.leading.trailing.mas_equalTo(self.view);
        make.height.mas_equalTo(1 * SCREENH6);
    }];
    
    [self.cardNumberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.nameLabel);
        make.top.mas_equalTo(self.oneLineView.mas_bottom).offset(25* SCREENH6);
    }];
    
    [self.cardNumberField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.cardNumberLabel);
        make.leading.height.width.mas_equalTo(self.nameField);
    }];
    
    [self.twoLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.oneLineView.mas_bottom).offset(65 * SCREENH6);
        make.leading.trailing.height.mas_equalTo(self.oneLineView);
    }];
    
    [self.showLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view).offset(15 * SCREENH6);
        make.trailing.mas_equalTo(self.view).offset(-15 * SCREENH6);
        make.top.mas_equalTo(self.twoLineView.mas_bottom).offset(10 * SCREENH6);
    }];
    
    [self.nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(345 * SCREENH6);
        make.height.mas_equalTo(46 * SCREENH6);
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.showLabel.mas_bottom).offset(130 * SCREENH6);
    }];
    
    [self.stateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.twoLineView.mas_bottom).offset(10 * SCREENH6);
    }];
}


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if ([self.canEdit isEqualToString:@"canEdit"]) {
        return YES;
    }
    return NO;
}


- (void)didNextButton{
    
    if ([self.nameField.text isEqualToString:@""] || [self.cardNumberField.text isEqualToString:@""]) {
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"请完善认证信息后提交！"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  //响应事件
                                                                  NSLog(@"action = %@", action);
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
        
    }else{
        
        NSDictionary * parametersDic = @{@"fullName":self.nameField.text,@"cardNo":self.cardNumberField.text};
        
        [[NetworkTool sharedTools] POST:@"user/real-name" parameters:parametersDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
            
            NSString * code = [NSString stringWithFormat:@"%@", responseObject[@"code"]];//responseObject[@"code"];
            
            if ([code isEqualToString:@"0"]) {
                
                AddIDCardImageViewController * adIDCard = [AddIDCardImageViewController new];
                
                [self.navigationController pushViewController:adIDCard animated:YES];
            }else{
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseObject[@"msg"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          //响应事件
                                                                          NSLog(@"action = %@", action);
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            NSLog(@"%@",error);
        }];
        
    }
    
    
}


//- (BOOL)isCorrect:(NSString *)IDNumber
//{
//    NSMutableArray *IDArray = [NSMutableArray array];
//    // 遍历身份证字符串,存入数组中
//    for (int i = 0; i < 18; i++) {
//        NSRange range = NSMakeRange(i, 1);
//        NSString *subString = [IDNumber substringWithRange:range];
//        [IDArray addObject:subString];
//    }
//    // 系数数组
//    NSArray *coefficientArray = [NSArray arrayWithObjects:@"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2", nil];
//    // 余数数组
//    NSArray *remainderArray = [NSArray arrayWithObjects:@"1", @"0", @"X", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2", nil];
//    // 每一位身份证号码和对应系数相乘之后相加所得的和
//    int sum = 0;
//    for (int i = 0; i < 17; i++) {
//        int coefficient = [coefficientArray[i] intValue];
//        int ID = [IDArray[i] intValue];
//        sum += coefficient * ID;
//    }
//    // 这个和除以11的余数对应的数
//    NSString *str = remainderArray[(sum % 11)];
//    // 身份证号码最后一位
//    NSString *string = [IDNumber substringFromIndex:17];
//    // 如果这个数字和身份证最后一位相同,则符合国家标准,返回YES
//    if ([str isEqualToString:string]) {
//        return YES;
//    } else {
//        return NO;
//    }
//}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.nameField resignFirstResponder];
    [self.cardNumberField resignFirstResponder];
    
}



- (void)backToAccountView{
    
    [self.navigationController popViewControllerAnimated:YES];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
